<template>
  <div 
    id="globalSider" 
    class="modern-sider"
    v-motion
    :initial="{ x: -240, opacity: 0 }"
    :enter="{ x: 0, opacity: 1, transition: { duration: 600, delay: 400 } }"
  >
    <div v-if="loginUserStore.loginUser.id" class="sider-content">
      <!-- 导航菜单 -->
      <div class="sider-menu">
        <!-- 固定菜单项 -->
        <div 
          v-for="(item, index) in fixedMenuItems" 
          :key="item.key"
          class="menu-item"
          :class="{ 
            active: current.includes(item.key)
          }"
          @click="handleMenuClick(item)"
          v-motion
          :initial="{ x: -30, opacity: 0 }"
          :enter="{ 
            x: 0, 
            opacity: 1, 
            transition: { 
              duration: 400, 
              delay: 700 + index * 100,
              ease: 'easeOut' 
            } 
          }"
        >
          <div class="menu-item-content">
            <div class="menu-icon-wrapper">
              <component :is="item.icon" class="menu-icon" />
              <div class="icon-ripple"></div>
            </div>
            <span class="menu-label">{{ item.label }}</span>
            <div class="menu-indicator"></div>
          </div>
        </div>

        <!-- 团队空间分组 -->
        <div 
          v-if="teamSpaceList.length > 0" 
          class="menu-group"
          v-motion
          :initial="{ y: 20, opacity: 0 }"
          :enter="{ y: 0, opacity: 1, transition: { duration: 500, delay: 1000 } }"
        >
          <div 
            class="group-header"
            @click="toggleTeamExpanded"
          >
            <div class="group-title">
              <TeamOutlined class="group-icon" />
              <span>我的团队</span>
            </div>
            <div 
              class="expand-arrow"
              :class="{ expanded: isTeamExpanded }"
            >
              <DownOutlined />
            </div>
          </div>
          
          <transition
            name="team-collapse"
            @enter="onTeamEnter"
            @leave="onTeamLeave"
          >
            <div 
              class="team-list"
              v-show="isTeamExpanded"
            >
              <div
                v-for="(spaceUser, index) in teamSpaceList"
                :key="spaceUser.spaceId"
                class="team-item"
                :class="{ active: current.includes('/space/' + (spaceUser.spaceId?.toString() || '')) }"
                @click="goToTeamSpace(spaceUser.spaceId?.toString() || '')"
                :style="{ animationDelay: `${index * 50}ms` }"
              >
                <div class="team-item-content">
                  <div class="team-avatar">
                    {{ spaceUser.space?.spaceName?.charAt(0) || 'T' }}
                  </div>
                  <div class="team-info">
                    <span class="team-name">{{ spaceUser.space?.spaceName }}</span>
                    <span class="team-role">{{ getUserRole(spaceUser.spaceRole || 'user') }}</span>
                  </div>
                </div>
              </div>
            </div>
          </transition>
        </div>

        <!-- 快捷操作 -->
        <div 
          class="quick-actions"
          v-motion
          :initial="{ y: 30, opacity: 0 }"
          :enter="{ y: 0, opacity: 1, transition: { duration: 500, delay: 1200 } }"
        >
          <div class="action-title">快捷操作</div>
          <div class="action-buttons">
            <button 
              class="action-btn"
              @click="goToUpload"
              title="上传图片"
            >
              <PlusOutlined />
            </button>
            <button 
              class="action-btn"
              @click="goToAnalyze"
              :title="getAnalyzeButtonTitle()"
            >
              <BarChartOutlined />
            </button>
            <button 
              class="action-btn"
              @click="toggleTheme"
              title="切换主题"
            >
              <BulbOutlined />
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 未登录状态 -->
    <div v-else class="login-prompt">
      <div class="login-prompt-content">
        <UserOutlined class="login-icon" />
        <h3>请先登录</h3>
        <p>登录后可以享受更多功能</p>
        <a-button 
          type="primary" 
          class="login-btn"
          @click="goToLogin"
        >
          立即登录
        </a-button>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { computed, h, ref, watchEffect } from 'vue'
import { 
  PictureOutlined, 
  TeamOutlined, 
  UserOutlined, 
  DownOutlined,
  PlusOutlined,
  BarChartOutlined,
  BulbOutlined,
  GiftOutlined,
  SoundOutlined
} from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { SPACE_TYPE_ENUM } from '@/constants/space.ts'
import { listMyTeamSpaceUsingPost } from '@/api/spaceUserController.ts'
import { listSpaceVoByPageUsingPost } from '@/api/spaceController.ts'
import { message } from 'ant-design-vue'
import { useTheme } from '@/composables/useTheme'

const loginUserStore = useLoginUserStore()
const router = useRouter()
const { toggleTheme } = useTheme()

// 状态管理
const teamSpaceList = ref<API.SpaceUserVO[]>([])
const current = ref<string[]>([])
const isTeamExpanded = ref(true)

// 基础菜单列表
const baseMenuItems = [
  {
    key: '/',
    icon: () => h(PictureOutlined),
    label: '公共图库',
  },
  {
    key: '/my_space',
    label: '我的空间',
    icon: () => h(UserOutlined),
  },
  {
    key: '/add_space',
    label: '创建团队',
    icon: () => h(TeamOutlined),
  },
]

// 管理员专用菜单
const adminMenuItems = [
  {
    key: '/admin/userManage',
    label: '用户管理',
    icon: () => h(UserOutlined),
  },
  {
    key: '/admin/pictureManage',
    label: '图片管理',
    icon: () => h(PictureOutlined),
  },
  {
    key: '/admin/spaceManage',
    label: '空间管理',
    icon: () => h(TeamOutlined),
  },
  {
    key: '/admin/careCodeManage',
    label: '卡密管理',
    icon: () => h(GiftOutlined),
  },
  {
    key: '/admin/announcementManage',
    label: '公告管理',
    icon: () => h(SoundOutlined),
  },
]

// 根据用户权限动态生成菜单列表
const fixedMenuItems = computed(() => {
  const items = [...baseMenuItems]
  // 如果是管理员，添加管理员菜单
  if (loginUserStore.loginUser.userRole === 'admin') {
    items.push(...adminMenuItems)
  }
  return items
})

// 加载团队空间列表
const fetchTeamSpaceList = async () => {
  const res = await listMyTeamSpaceUsingPost()
  if (res.data.code === 0 && res.data.data) {
    teamSpaceList.value = res.data.data
  } else {
    message.error('加载我的团队空间失败，' + res.data.message)
  }
}

/**
 * 监听变量，改变时触发数据的重新加载
 */
watchEffect(() => {
  // 登录才加载
  if (loginUserStore.loginUser.id) {
    fetchTeamSpaceList()
  }
  
  // 设置当前路由高亮
  let initialPath = router.currentRoute.value.path
  // 如果是空间详情页面 (/space/{id})，则高亮"我的空间"
  if (initialPath.startsWith('/space/')) {
    initialPath = '/my_space'
  }
  current.value = [initialPath]
})

// 监听路由变化，更新高亮菜单项
router.afterEach((to, from, next) => {
  // 获取当前路径，去掉查询参数
  let currentPath = to.path
  
  // 如果是空间详情页面 (/space/{id})，则高亮"我的空间"
  if (currentPath.startsWith('/space/')) {
    currentPath = '/my_space'
  }
  
  current.value = [currentPath]
})

// 菜单点击处理
const handleMenuClick = (item: any) => {
  if (item.key === '/add_space') {
    // 创建团队需要添加type参数
    router.push({
      path: item.key,
      query: { type: SPACE_TYPE_ENUM.TEAM }
    })
  } else {
    router.push(item.key)
  }
}

// 团队空间相关
const toggleTeamExpanded = () => {
  isTeamExpanded.value = !isTeamExpanded.value
}

// 团队列表折叠动画
const onTeamEnter = (el: Element) => {
  const element = el as HTMLElement
  element.style.height = '0'
  element.style.overflow = 'hidden'
  
  // 强制重流
  element.offsetHeight
  
  // 获取实际高度
  element.style.height = 'auto'
  const height = element.offsetHeight
  element.style.height = '0'
  
  // 动画展开
  requestAnimationFrame(() => {
    element.style.transition = 'height 0.3s cubic-bezier(0.4, 0, 0.2, 1)'
    element.style.height = height + 'px'
    
    setTimeout(() => {
      element.style.height = 'auto'
      element.style.overflow = 'visible'
      element.style.transition = ''
    }, 300)
  })
}

const onTeamLeave = (el: Element) => {
  const element = el as HTMLElement
  const height = element.offsetHeight
  
  element.style.height = height + 'px'
  element.style.overflow = 'hidden'
  
  requestAnimationFrame(() => {
    element.style.transition = 'height 0.3s cubic-bezier(0.4, 0, 0.2, 1)'
    element.style.height = '0'
  })
}

const goToTeamSpace = (spaceId: string) => {
  router.push(`/space/${spaceId}`)
}

const getUserRole = (role: string) => {
  const roleMap: { [key: string]: string } = {
    admin: '管理员',
    user: '成员',
    owner: '所有者'
  }
  return roleMap[role] || '成员'
}

// 获取分析按钮的提示文本
const getAnalyzeButtonTitle = () => {
  if (loginUserStore.loginUser?.userRole === 'admin') {
    return '查看公共图库分析'
  } else {
    return '查看我的私有空间分析'
  }
}

// 快捷操作
const goToUpload = () => {
  router.push('/add_picture')
}

const goToAnalyze = async () => {
  try {
    // 判断用户角色
    if (loginUserStore.loginUser?.userRole === 'admin') {
      // 管理员：跳转到公共图库分析
      router.push('/space_analyze?queryPublic=1')
    } else {
      // 普通用户：跳转到自己的私有空间分析
      // 先获取用户的私有空间列表
      console.log('正在获取用户私有空间列表...')
      const res = await listSpaceVoByPageUsingPost({
        userId: loginUserStore.loginUser.id, // 重要：指定用户ID，只获取当前用户的空间
        current: 1,
        pageSize: 10,
        spaceType: SPACE_TYPE_ENUM.PRIVATE,
        sortField: 'createTime',
        sortOrder: 'descend'
      })
      
      console.log('私有空间列表响应:', res.data)
      
      if (res.data.code === 0 && res.data.data?.records && res.data.data.records.length > 0) {
        // 获取用户的第一个私有空间
        const privateSpace = res.data.data.records[0]
        console.log('找到的私有空间:', privateSpace)
        
        if (privateSpace.id) {
          // 跳转到用户的私有空间分析页面
          const analyzeUrl = `/space_analyze?spaceId=${privateSpace.id}`
          console.log('跳转到:', analyzeUrl)
          router.push(analyzeUrl)
        } else {
          message.warning('获取空间ID失败')
          router.push('/add_space')
        }
      } else {
        console.log('没有找到私有空间，响应详情:', res.data)
        message.warning('您还没有私有空间，请先创建一个空间')
        router.push('/add_space')
      }
    }
  } catch (error) {
    console.error('获取空间信息失败:', error)
    message.error('获取空间信息失败，请稍后重试')
  }
}

const goToLogin = () => {
  router.push('/user/login')
}
</script>

<style scoped>
.modern-sider {
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
}

.sider-content {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}


/* 导航菜单 */
.sider-menu {
  flex: 1;
  padding: 1rem 0.5rem 0 0.5rem;
}

.menu-item {
  position: relative;
  margin-bottom: 0.5rem;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.menu-item:hover {
  background: rgba(14, 165, 233, 0.08);
  transform: translateX(4px);
}

.menu-item.active {
  background: linear-gradient(135deg, rgba(14, 165, 233, 0.15), rgba(59, 130, 246, 0.15));
  border-left: 3px solid #0ea5e9;
}

.menu-item.active .menu-indicator {
  opacity: 1;
  transform: scaleX(1);
}

.menu-item.active .menu-icon {
  color: #0ea5e9;
  transform: scale(1.1);
}

.menu-item-content {
  display: flex;
  align-items: center;
  padding: 0.875rem 1rem;
  position: relative;
}

.menu-icon-wrapper {
  position: relative;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 0.75rem;
}

.menu-icon {
  font-size: 1.125rem;
  color: var(--text-secondary);
  transition: all 0.3s ease;
  z-index: 2;
  position: relative;
}

.icon-ripple {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  background: rgba(14, 165, 233, 0.2);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: all 0.3s ease;
}

.menu-item:hover .icon-ripple {
  width: 40px;
  height: 40px;
}

.menu-label {
  font-size: 0.9rem;
  font-weight: 500;
  color: var(--text-primary);
  flex: 1;
}

.menu-indicator {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  background: linear-gradient(135deg, #0ea5e9, #3b82f6);
  opacity: 0;
  transform: scaleX(0);
  transition: all 0.3s ease;
  border-radius: 0 2px 2px 0;
}

/* 团队空间分组 */
.menu-group {
  margin: 1.5rem 0;
}

.group-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.75rem 1rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 0.5rem;
}

[data-theme="dark"] .group-header {
  background: rgba(31, 41, 55, 0.3);
}

.group-header:hover {
  background: rgba(14, 165, 233, 0.08);
}

.group-title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.875rem;
  font-weight: 600;
  color: var(--text-secondary);
}

.group-icon {
  font-size: 1rem;
  color: #0ea5e9;
}

.expand-arrow {
  font-size: 0.75rem;
  color: var(--text-muted);
  transition: transform 0.3s ease;
}

.expand-arrow.expanded {
  transform: rotate(180deg);
}

.team-list {
  margin-left: 1rem;
}

.team-item {
  padding: 0.625rem 1rem;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 0.25rem;
  border-left: 2px solid transparent;
}

.team-item:hover {
  background: rgba(14, 165, 233, 0.06);
  border-left-color: rgba(14, 165, 233, 0.3);
  transform: translateX(2px);
}

.team-item.active {
  background: rgba(14, 165, 233, 0.1);
  border-left-color: #0ea5e9;
}

.team-item-content {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.team-avatar {
  width: 28px;
  height: 28px;
  border-radius: 6px;
  background: linear-gradient(135deg, #0ea5e9, #3b82f6);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.75rem;
  font-weight: 600;
}

.team-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.team-name {
  font-size: 0.875rem;
  font-weight: 500;
  color: var(--text-primary);
  line-height: 1.2;
}

.team-role {
  font-size: 0.75rem;
  color: var(--text-muted);
}

/* 团队列表折叠动画 */
.team-collapse-enter-active,
.team-collapse-leave-active {
  overflow: hidden;
}

.team-collapse-enter-from,
.team-collapse-leave-to {
  height: 0;
  opacity: 0;
}

/* 团队项目动画 */
.team-item {
  animation: teamItemFadeIn 0.3s ease forwards;
  opacity: 0;
  transform: translateX(-10px);
}

@keyframes teamItemFadeIn {
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 快捷操作 */
.quick-actions {
  margin-top: auto;
  padding: 1rem;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.action-title {
  font-size: 0.75rem;
  font-weight: 600;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing: 0.5px;
  margin-bottom: 0.75rem;
}

.action-buttons {
  display: flex;
  gap: 0.5rem;
}

.action-btn {
  flex: 1;
  width: 40px;
  height: 40px;
  border: none;
  border-radius: 10px;
  background: rgba(255, 255, 255, 0.1);
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1rem;
  backdrop-filter: blur(10px);
}

[data-theme="dark"] .action-btn {
  background: rgba(31, 41, 55, 0.3);
}

.action-btn:hover {
  background: rgba(14, 165, 233, 0.15);
  color: #0ea5e9;
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(14, 165, 233, 0.2);
}

/* 未登录状态 */
.login-prompt {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem 1rem;
}

.login-prompt-content {
  text-align: center;
  max-width: 200px;
}

.login-icon {
  font-size: 3rem;
  color: var(--text-muted);
  margin-bottom: 1rem;
}

.login-prompt h3 {
  margin: 0 0 0.5rem 0;
  font-size: 1.125rem;
  color: var(--text-primary);
}

.login-prompt p {
  margin: 0 0 1.5rem 0;
  font-size: 0.875rem;
  color: var(--text-secondary);
  line-height: 1.5;
}

.login-btn {
  width: 100%;
  border-radius: 8px !important;
  font-weight: 600 !important;
}

/* 滚动条样式 */
.modern-sider::-webkit-scrollbar {
  width: 4px;
}

.modern-sider::-webkit-scrollbar-track {
  background: transparent;
}

.modern-sider::-webkit-scrollbar-thumb {
  background: rgba(14, 165, 233, 0.3);
  border-radius: 2px;
}

.modern-sider::-webkit-scrollbar-thumb:hover {
  background: rgba(14, 165, 233, 0.5);
}

/* 移除Ant Design默认样式 */
:deep(.ant-layout-sider) {
  background: transparent !important;
}

:deep(.ant-menu) {
  background: transparent !important;
  border: none !important;
}

:deep(.ant-menu-item) {
  background: transparent !important;
  border: none !important;
  margin: 0 !important;
  padding: 0 !important;
  height: auto !important;
  line-height: normal !important;
}

:deep(.ant-menu-item-selected) {
  background: transparent !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .menu-item-content {
    justify-content: center;
    padding: 0.75rem;
  }
  
  .menu-label {
    display: none;
  }
  
  .menu-icon-wrapper {
    margin-right: 0;
  }
  
  .quick-actions {
    padding: 0.75rem 0.5rem;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 0.375rem;
  }
  
  .action-btn {
    width: 100%;
    height: 36px;
  }
  
  .team-list {
    margin-left: 0;
  }
}

/* 动画关键帧 */
@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}
</style>
